package com.bestcem.xm.om.service.impl;

import com.bestcem.xm.om.config.properties.OmSmsProperties;
import com.bestcem.xm.om.grpc.client.SendSingleGrpcService;
import com.bestcem.xm.om.service.SmsService;
import com.wenjuan.bp.sms.grpc.sms.v1.SendSingleRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信发送服务实现类
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/24 11:42
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    private OmSmsProperties omSmsProperties;
    @Resource
    private SendSingleGrpcService omSendSingleGrpcService;

    @Override
    public boolean smsSingleSend(String phone, String content, String id) {
        if (StringUtils.isAnyEmpty(phone, content)) {
            log.error("[OM] 手机号或发送内容不能为空 phone:{} content:{}", phone, content);
            return false;
        }
        int templateId = this.getDefaultTemplateId();
        List<String> paramList = new ArrayList<>();
        paramList.add(content);
        Map<String, String> paramMap = this.generateParamMap(templateId, paramList);
        SendSingleRequest request = SendSingleRequest.newBuilder()
                .setPhone(phone).setTemplateId(templateId).setOutId(id).putAllParameter(paramMap).build();

        return omSendSingleGrpcService.sendSingle(request);
    }

    @Override
    public Integer getDefaultTemplateId() {
        return omSmsProperties.getTemplateId();
    }

    @Override
    public Map<String, String> generateParamMap(int templateId, List<String> praramList) {
        Map<String, String> paramMap = new HashMap<>(16);
        if (CollectionUtils.isEmpty(praramList)) {
            return paramMap;
        }

        paramMap.put(omSmsProperties.getTemplateKey(), praramList.get(0));
        return paramMap;
    }
}
